package com.app.demo.converter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.app.core.mvc.serialization.EnumDefinition;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author 00351634
 * @version 1.0
 * @date 2024/7/19 8:23
 * @description: easy excel 枚举转换器
 */
public class ExcelEunmConverter implements Converter<EnumDefinition> {
    @Override
    public Class supportJavaTypeKey() {
        return EnumDefinition.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public EnumDefinition convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String cellValue = StrUtil.isNotBlank(cellData.getStringValue()) ? cellData.getStringValue() : Convert.toStr(cellData.getNumberValue());
        if (StrUtil.isNotBlank(cellValue)) {
            Class<?> enumClass = contentProperty.getField().getType();
            try {
                Method getComment = enumClass.getMethod("getComment");
                for (Object enumConstant : enumClass.getEnumConstants()) {
                    Object comment = getComment.invoke(enumConstant);
                    if (Objects.equals(comment.toString(), cellValue)) {
                        return (EnumDefinition) enumConstant;
                    }
                }
                throw new IllegalStateException("枚举参数异常");
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        return null;
    }

    @Override
    public WriteCellData<?> convertToExcelData(EnumDefinition value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        ExcelEnumFormat excelEnumFormat = contentProperty.getField().getDeclaredAnnotation(ExcelEnumFormat.class);
        if (Objects.nonNull(excelEnumFormat)) {
            switch (excelEnumFormat.format()) {
                case CODE:
                    return new WriteCellData<>(Convert.toStr(value.getCode()));
                case NAME:
                    return new WriteCellData<>(value.getComment());
                case CODE_NAME:
                    return new WriteCellData<>(value.getComment() + "(" + value.getCode() + ")");
                default:
                    return new WriteCellData<>(value.getComment());
            }
        }
        return new WriteCellData<>(value.getComment());
    }

}
